<template>
	<cl-dialog
		v-model="visible"
		class="zhongtian-add-order"
		width="90%"
		:close-on-click-modal="false"
	>
		<el-card shadow="never">
			<template #header>
				<div class="card-header">
					<span>镜片订单添加</span>
				</div>
			</template>
			<el-form ref="formRef" :model="formData" label-width="120px">
				<el-divider content-position="left">订单信息</el-divider>
				<el-row>
					<el-col :span="12">
						<el-form-item label="用户">
							<el-input v-model="order_info.userNickName" readonly="" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="手机号">
							<el-input v-model="order_info.userPhone" readonly="" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="购买时间">
							<el-input v-model="order_info.createTime" readonly="" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="支付金额">
							<el-input v-model="order_info.payAmount" readonly="" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="订单类型">
							<span>{{ order_info.orderType === 'customerOrder' ? '客情订单' : order_info.orderType ? order_info.orderType : '正常订单' }}</span>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="镜片数量">
							<span>{{ order_info.lensQuantity === 1 ? '左眼' : order_info.lensQuantity === 2 ? '右眼' : order_info.lensQuantity === 0 ? '一副镜片' : '镜片数量错误' }}</span>
						</el-form-item>
					</el-col>
					<el-col v-if="order_info.payImg" :span="12">
						<el-form-item label="支付截图">
							<cl-upload v-model="order_info.payImg" disabled />
						</el-form-item>
					</el-col>
           		<el-col :span="12">
					<el-form-item label="验光单">
							<cl-upload v-model="order_info.eyeglassImg" />
						</el-form-item>
					</el-col>
				</el-row>

				<el-divider content-position="left">收货数据</el-divider>
				<el-row>
					<el-col :span="12">
						<el-form-item label="城市" prop="data.o.c_shop_name">
							<el-input v-model="shop_info.cityName" readonly="" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="店铺名称" prop="data.o.c_shop_name">
							<el-input v-model="shop_info.name" readonly="" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="收货人" prop="data.o.c_shop_name">
							<el-input v-model="formData.contactName" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="收货电话" prop="data.o.c_shop_name">
							<el-input v-model="formData.contactPhone" />
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="收货地址" prop="data.o.c_shop_name">
							<el-input v-model="formData.receiveAddress" />
						</el-form-item>
					</el-col>

					<el-col :span="12">
						<el-form-item label="用户名" prop="data.o.c_shop_name">
							<el-input v-model="remarkObj.userName" />
						</el-form-item>
					</el-col>

					<el-col :span="12">
						<el-form-item label="订单备注" prop="data.o.c_shop_name">
							<el-input v-model="remarkObj.remark" />
						</el-form-item>
					</el-col>

					<el-col style="display: none" :span="12">
						<el-form-item label="订单备注" prop="data.o.remark">
							<el-input v-model="formData.remark" readonly />
						</el-form-item>
					</el-col>
				</el-row>

				<!-- 验光数据（可选） -->
				<el-divider content-position="left">镜片数据</el-divider>

				<el-row :gutter="20">
					<el-col :span="12">
						<el-form-item label="镜片选择" prop="data.o.c_goods_l">
							<div class="inline-flex-container">
								<el-select
									v-if="goodsList.length > 0"
									v-model="formData.c_goods_l"
									placeholder="请选择镜片"
									style="width: auto; min-width: 300px; margin-right: 8px"
								>
									<el-option
										v-for="item in goodsList"
										:key="item.lens_code"
										:label="item.lens_desc"
										:value="item.lens_code"
									/>
								</el-select>
								<!-- <div style="display: flex; align-items: center;">
                      <span style="margin-right: 4px;">数量：</span>
                      <el-input v-model="formData.c_lnum" placeholder="请输入采购数量" style="width: 100px;" />
                  </div> -->
							</div>
						</el-form-item>
					</el-col>
					<!-- 镀膜类型 -->
					<el-col :span="12">
						<el-form-item label="镀膜" prop="data.o.c_coating_type">
							<el-select
								v-model="formData.c_coating_type"
								placeholder="请选择镀膜类型"
								style="width: 100%"
							>
								<el-option
									v-for="item in processList.coatingType"
									:key="item.value"
									:label="item.label"
									:value="item.value"
								/>
							</el-select>
						</el-form-item>
					</el-col>

					<!-- <el-col :span="12">
                <el-form-item label="左镜片" prop="data.o.c_goods_r">
                    <div class="inline-flex-container">
                        <el-select v-if="goodsList.length > 0" v-model="formData.c_goods_r" placeholder="请选择右镜片" style="width: auto; min-width: 300px; margin-right: 8px;">
                            <el-option v-for="item in goodsList" :key="item.lens_code" :label="item.lens_desc" :value="item.lens_code" />
                        </el-select>
                        <div style="display: flex; align-items: center;">
                            <span style="margin-right: 4px;">数量：</span>
                            <el-input v-model="formData.c_rnum" placeholder="请输入采购数量" style="width: 100px;" />
                        </div>
                    </div>
                </el-form-item>
            </el-col> -->
					<el-col :span="12">
							<el-form-item label="右直径R" prop="data.o.c_diar">
								<el-input v-model="formData.c_diar" placeholder="例子：75" :disabled="order_info.lensQuantity === 1" />
							</el-form-item>
						</el-col>

					<el-col :span="12">
							<el-form-item label="左直径R" prop="data.o.c_dial">
								<el-input v-model="formData.c_dial" placeholder="例子：75" :disabled="order_info.lensQuantity === 2" />
							</el-form-item>
						</el-col>

					<el-col :span="12">
							<el-form-item label="右球镜" prop="c_rball">
								<el-input v-model.number="formData.c_rball" placeholder="例子：-500" :disabled="order_info.lensQuantity === 1" />
							</el-form-item>
						</el-col>

					<el-col :span="12">
							<el-form-item label="左球镜" prop="c_lball">
								<el-input v-model.number="formData.c_lball" placeholder="例子：-500" :disabled="order_info.lensQuantity === 2" />
							</el-form-item>
						</el-col>

					<el-col :span="12">
							<el-form-item label="右柱镜" prop="c_rpole">
								<el-input v-model.number="formData.c_rpole" placeholder="例子：-150" :disabled="order_info.lensQuantity === 1" />
							</el-form-item>
						</el-col>

					<el-col :span="12">
							<el-form-item label="左柱镜" prop="c_lpole">
								<el-input v-model.number="formData.c_lpole" placeholder="例子：-150" :disabled="order_info.lensQuantity === 2" />
							</el-form-item>
						</el-col>

					<el-col :span="12" v-if="showAddFields">
							<el-form-item label="右后表面离焦量" prop="data.o.c_radd">
								<el-input v-model="formData.c_radd" placeholder="例子：100" :disabled="order_info.lensQuantity === 1" />
							</el-form-item>
						</el-col>

					<el-col :span="12" v-if="showAddFields">
							<el-form-item label="左后表面离焦量" prop="data.o.c_ladd">
								<el-input v-model="formData.c_ladd" placeholder="例子：100" :disabled="order_info.lensQuantity === 2" />
							</el-form-item>
						</el-col>

					<el-col :span="12">
							<el-form-item label="右散光轴向" prop="data.o.c_rpole">
								<el-input v-model="formData.c_rline" placeholder="例子：179" :disabled="order_info.lensQuantity === 1" />
							</el-form-item>
						</el-col>

					<el-col :span="12">
							<el-form-item label="左散光轴向" prop="data.o.c_lpole">
								<el-input v-model="formData.c_lline" placeholder="例子：179" :disabled="order_info.lensQuantity === 2" />
							</el-form-item>
						</el-col>

					<el-col :span="12">
							<el-form-item label="右瞳距" prop="data.o.c_rpole">
								<el-input v-model="formData.pd_r" placeholder="例子：179" :disabled="order_info.lensQuantity === 1" />
							</el-form-item>
						</el-col>

					<el-col :span="12">
							<el-form-item label="左瞳距" prop="data.o.c_lpole">
								<el-input v-model="formData.pd_l" placeholder="例子：179" :disabled="order_info.lensQuantity === 2" />
							</el-form-item>
						</el-col>

					<el-col :span="12">
							<el-form-item label="右瞳高" prop="data.o.c_rpole">
								<el-input v-model="formData.ph_r" placeholder="例子：179" :disabled="order_info.lensQuantity === 1" />
							</el-form-item>
						</el-col>

					<el-col :span="12">
							<el-form-item label="左瞳高" prop="data.o.c_lpole">
								<el-input v-model="formData.ph_l" placeholder="例子：179" :disabled="order_info.lensQuantity === 2" />
							</el-form-item>
						</el-col>

					<el-divider content-position="left">加工模块</el-divider>
					<!-- 是否加工 -->
					<el-col :span="12">
						<el-form-item label="加工" prop="data.o.c_is_process">
							<el-radio-group v-model="formData.c_is_process">
								<el-radio label="1">是</el-radio>
								<el-radio label="0">否</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>

					<!-- 加工模块：只在加工选择为"是"时显示 -->
					<el-col :span="24" v-if="formData.c_is_process === '1'">
						<el-row :gutter="20">
							<!-- 加工方式 -->
							<el-col :span="12">
								<el-form-item label="加工方式" prop="data.o.c_process_type">
									<el-select
										v-model="formData.c_process_type"
										placeholder="请选择加工方式"
										style="width: 100%"
									>
										<el-option
											v-for="item in processList.processType"
											:key="item.value"
											:label="item.label"
											:value="item.value"
										/>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="眼镜品牌" prop="data.o.c_shop_name">
									<el-input v-model="remarkObj.brand" />
								</el-form-item>
							</el-col>

							<el-col :span="12">
								<el-form-item label="眼镜型号" prop="data.o.c_shop_name">
									<el-input v-model="remarkObj.model" />
								</el-form-item>
							</el-col>

							<el-col :span="12">
								<el-form-item label="眼镜颜色" prop="data.o.c_shop_name">
									<el-input v-model="remarkObj.frameColor" />
								</el-form-item>
							</el-col>

							<el-col :span="12">
								<el-form-item label="镜框物流单号" prop="data.o.c_shop_name">
									<el-input v-model="remarkObj.logisticsNo" />
								</el-form-item>
							</el-col>
						</el-row>
					</el-col>
				</el-row>
				<!-- 操作按钮 -->
				<div class="form-actions">
					<el-button type="primary" @click="checkForm" :disabled="isSubmit">提交订单</el-button>
					<!-- <el-button type="success" :disabled="!checkOrder" @click="submitForm">提交订单</el-button> -->
					<!-- <el-button @click="resetForm">重置</el-button> -->
					<el-button @click="closeDialog">关闭</el-button>
				</div>
			</el-form>
		</el-card>
	</cl-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, defineExpose, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { useCool } from '/@/cool';
import { useI18n } from 'vue-i18n';
import { sleep } from '/@/cool/utils';

const { service } = useCool();
const { t } = useI18n();
const formRef = ref();
const visible = ref(false);
const emit = defineEmits(['closeDialog', 'update:modelValue']);

const props = defineProps({
	orderId: {
		type: Number,
		default: 0
	},
	modelValue: {
		type: Boolean,
		default: false
	}
});

// 加工列表参数
const processList = ref({
	processType: [],
	coatingType: []
});

const remarkObj = ref({
	// 品牌
	brand: '',
	// 眼镜型号
	model: '',
	// 镜框颜色
	frameColor: '',
	// 物流单号
	logisticsNo: '',
	// 配镜用户
	userName: '',
	// 备注字符串
	remark: ''
});

// 表单数据
const formData = reactive({
	contactName: '',
	contactPhone: '',
	receiveAddress: '',
	c_dial: '',
	c_diar: '',
	c_lball: '',
	c_rball: '',
	c_lpole: '',
	c_rpole: '',
	c_goods_l: '',
	c_goods_r: '',
	c_goods_left_list: [],
	c_goods_right_list: [],
	c_lnum: '',
	c_rnum: '',
	c_ladd: '',
	c_radd: '',
	c_lline: '',
	c_rline: '',
	c_goods_l_desc: '',
	c_goods_r_desc: '',
	order_id: props.orderId,
	c_is_process: '0',
	pd_r: 0,
	pd_l: 0,
	ph_r: 0,
	ph_l: 0,
	remark: '',
	// 新增加工相关字段
	c_process_type: '', // 加工方式
	c_coating_type: '', // 镀膜类型
	c_process_type_name: '', // 加工方式名称
	c_coating_type_name: '', // 镀膜类型名称
	lensQuantity: -1, // 镜片数量
	eyeglassImg: null,
});

// 表单校验规则
const rules = {};

// 在remarkObj改变时，拼上remark
watch(
	remarkObj,
	(newVal, oldVal) => {
		console.log(remarkObj);
		formData.remark = `${newVal.userName},${newVal.brand},${newVal.model},${newVal.frameColor},${newVal.logisticsNo},${newVal.remark}`;
	},
	{ deep: true }
);

const shop_info = ref({});
const order_info = ref({});
const checkOrder = ref(false);
const isEdit = ref(false);
const updateShopInfo = ref(true);
const isSubmit = ref(false);

// 获取店铺信息
async function getShopInfoByOrderId(orderId) {
	// 如果是编辑的直接返回
	console.log('getShopInfoByOrderId', updateShopInfo.value);

	const res = await service.order.shop.getShopInfoByOrderId({
		orderId: orderId
	});
	shop_info.value = res;
	if (!updateShopInfo.value) {
		return;
	}
	formData.contactName = res.contactName;
	formData.contactPhone = res.contactPhone;
	formData.receiveAddress = res.receiveAddress;
}

// 检查订单
async function checkForm() {
	if (formData.c_goods_l == '') {
		ElMessage.error('请选择镜片');
		return;
	}
	// 收货信息不能为空
	if (
		formData.contactName == null ||
		formData.contactPhone == null ||
		formData.receiveAddress == null
	) {
		ElMessage.error('请填写收货信息');
		return;
	}
	// 收货信息不能为空
	if (
		formData.contactName == '' ||
		formData.contactPhone == '' ||
		formData.receiveAddress == ''
	) {
		ElMessage.error('请填写收货信息');
		return;
	}
	// 眼镜品牌不能为空
	if (remarkObj.value.brand == '' && formData.c_is_process === '1') {
		ElMessage.error('请填写眼镜品牌');
		return;
	}

	// 眼镜型号不能为空
	if (remarkObj.value.model == '' && formData.c_is_process === '1') {
		ElMessage.error('请填写眼镜型号');
		return;
	}
	// 镜框颜色不能为空
	if (remarkObj.value.frameColor == '' && formData.c_is_process === '1') {
		ElMessage.error('请填写眼镜颜色');
		return;
	}
	// 物流单号不能为空
	if (remarkObj.value.logisticsNo == '' && formData.c_is_process === '1') {
		ElMessage.error('请填写镜框物流单号');
		return;
	}
	if (formData.c_coating_type == '') {
		ElMessage.error('请选择镀膜类型');
		return;
	}

	// 根据code找到镜片的desc
	let goods_l_desc = '';
	goodsList.value.forEach(item => {
		if (item.lens_code == formData.c_goods_l) {
			goods_l_desc = item.lens_desc;
		}
	});
	formData.c_goods_r = formData.c_goods_l;
	formData.c_goods_l_desc = goods_l_desc;
	formData.c_goods_r_desc = goods_l_desc;
	formData.order_id = props.orderId;

	if (
		(formData.c_dial === '' ||
		formData.c_diar === '' ||
		formData.c_lball === '' ||
		formData.c_rball === '' ||
		formData.c_lpole === '' ||
		formData.c_rpole === '' ||
		formData.c_lline === '' ||
		formData.c_rline === '') && order_info.value.lensQuantity == 0
	) {
		ElMessage.error('请填写完整订单信息');
		return;
	}
	if (
		(formData.c_dial === '' ||
		formData.c_lball === '' ||
		formData.c_lpole === '' ||
		formData.c_lline === '' ) && order_info.value.lensQuantity == 1
	) {
		ElMessage.error('请填写完整订单信息');
		return;
	}
	if (
		(formData.c_diar === '' ||
		formData.c_rball === '' ||
		formData.c_rpole === '' ||
		formData.c_rline === '') && order_info.value.lensQuantity == 2
	) {
		ElMessage.error('请填写完整订单信息');
		return;
	}
	// 如果有下加光则检查是否填写
	if (showAddFields.value) {
		if ((formData.c_ladd == '' || formData.c_radd == '') && order_info.value.lensQuantity == 0) {
			ElMessage.error('请填写下加光信息');
			return;
		}
		if ((formData.c_ladd == '') && order_info.value.lensQuantity == 1) {
			ElMessage.error('请填写下加光信息');
			return;
		}
		if ((formData.c_radd == '') && order_info.value.lensQuantity == 2) {
			ElMessage.error('请填写下加光信息');
			return;
		}
	}

	const rball = Number(formData.c_rball)
	const lball = Number(formData.c_lball)
	const rpole = Number(formData.c_rpole)
	const lpole = Number(formData.c_lpole)
	const lensQuantity = order_info.value.lensQuantity

	if (formData.c_goods_l == 'OSK159HKOOFETC') {
		// 标准版
		if (lensQuantity == 1 || lensQuantity == 0) {
			if (lball >= -400 && lball <= 100 && lpole <= 0 && lpole >= -200) {

			} else {
				ElMessage.error('此产品不支持当前度数无法生产，如有需要请联系代理商');
				return;
			}
		}
		// 标准版
		if (lensQuantity == 2 || lensQuantity == 0) {
			if (rball >= -400 && rball <= 100 && rpole <= 0 && rpole >= -200) {

			} else {
				ElMessage.error('此产品不支持当前度数无法生产，如有需要请联系代理商');
				return;
			}
		}
	} else if (formData.c_goods_l == 'OTK159HKOOFETC' || formData.c_goods_l == 'OTK159HKONFETC') {
		if (lensQuantity == 1 || lensQuantity == 0) {
			if (lball > 0 && lball <= 100 && lpole <= 0 && lpole >= -200) {
			} else if (lball <= 0 && lball >= -625 && lpole <= 0 && lpole >= -400) {
				// } else if (lball < -625 && lpole + lball >= -1000) {
			} else if (lball < -625 && lball >= -650 && lpole <= 0 && lpole >= -375) {
				// -650 到 -626 的区间判断
			} else if (lball < -650 && lball >= -675 && lpole <= 0 && lpole >= -350) {
				// -675 到 -651 的区间判断
			} else if (lball < -675 && lball >= -700 && lpole <= 0 && lpole >= -325) {
				// -700 到 -676 的区间判断
			} else if (lball < -700 && lball >= -725 && lpole <= 0 && lpole >= -300) {
				// -725 到 -701 的区间判断
			} else if (lball < -725 && lball >= -750 && lpole <= 0 && lpole >= -275) {
				// -750 到 -726 的区间判断
			} else if (lball < -750 && lball >= -775 && lpole <= 0 && lpole >= -250) {
				// -775 到 -751 的区间判断
			} else if (lball < -775 && lball >= -800 && lpole <= 0 && lpole >= -225) {
				// -800 到 -776 的区间判断
			} else if (lball < -800 && lball >= -825 && lpole <= 0 && lpole >= -200) {
				// -825 到 -801 的区间判断
			} else if (lball < -825 && lball >= -850 && lpole <= 0 && lpole >= -175) {
				// -850 到 -826 的区间判断
			} else if (lball < -850 && lball >= -875 && lpole <= 0 && lpole >= -150) {
				// -875 到 -851 的区间判断
			} else if (lball < -875 && lball >= -900 && lpole <= 0 && lpole >= -125) {
				// -900 到 -876 的区间判断
			} else if (lball < -900 && lball >= -925 && lpole <= 0 && lpole >= -100) {
				// -925 到 -901 的区间判断
			} else if (lball < -925 && lball >= -950 && lpole <= 0 && lpole >= -75) {
				// -950 到 -926 的区间判断
			} else if (lball < -950 && lball >= -975 && lpole <= 0 && lpole >= -50) {
				// -975 到 -951 的区间判断
			} else if (lball < -975 && lball > -1000 && lpole <= 0 && lpole >= -25) {
				// -999 到 -976 的区间判断
			} else if (lball == -1000 && lpole == 0) {
			} else {
				ElMessage.error('此产品不支持当前度数无法生产，如有需要请联系代理商');
				return;
			}
		}

		if (lensQuantity == 2 || lensQuantity == 0) {
			if (rball > 0 && rball <= 100 && rpole <= 0 && rpole >= -200) {
			} else if (rball <= 0 && rball >= -625 && rpole <= 0 && rpole >= -400) {
				// } else if (rball < -625 && rpole + rball >= -1000) {
			} else if (rball < -625 && rball >= -650 && rpole <= 0 && rpole >= -375) {
				// -650 到 -626 的区间判断
			} else if (rball < -650 && rball >= -675 && rpole <= 0 && rpole >= -350) {
				// -675 到 -651 的区间判断
			} else if (rball < -675 && rball >= -700 && rpole <= 0 && rpole >= -325) {
				// -700 到 -676 的区间判断
			} else if (rball < -700 && rball >= -725 && rpole <= 0 && rpole >= -300) {
				// -725 到 -701 的区间判断
			} else if (rball < -725 && rball >= -750 && rpole <= 0 && rpole >= -275) {
				// -750 到 -726 的区间判断
			} else if (rball < -750 && rball >= -775 && rpole <= 0 && rpole >= -250) {
				// -775 到 -751 的区间判断
			} else if (rball < -775 && rball >= -800 && rpole <= 0 && rpole >= -225) {
				// -800 到 -776 的区间判断
			} else if (rball < -800 && rball >= -825 && rpole <= 0 && rpole >= -200) {
				// -825 到 -801 的区间判断
			} else if (rball < -825 && rball >= -850 && rpole <= 0 && rpole >= -175) {
				// -850 到 -826 的区间判断
			} else if (rball < -850 && rball >= -875 && rpole <= 0 && rpole >= -150) {
				// -875 到 -851 的区间判断
			} else if (rball < -875 && rball >= -900 && rpole <= 0 && rpole >= -125) {
				// -900 到 -876 的区间判断
			} else if (rball < -900 && rball >= -925 && rpole <= 0 && rpole >= -100) {
				// -925 到 -901 的区间判断
			} else if (rball < -925 && rball >= -950 && rpole <= 0 && rpole >= -75) {
				// -950 到 -926 的区间判断
			} else if (rball < -950 && rball >= -975 && rpole <= 0 && rpole >= -50) {
				// -975 到 -951 的区间判断
			} else if (rball < -975 && rball > -1000 && rpole <= 0 && rpole >= -25) {
				// -999 到 -976 的区间判断
			} else if (rball == -1000 && rpole == 0) {
			} else {
				ElMessage.error('此产品不支持当前度数无法生产，如有需要请联系代理商');
				return;
			}
		}
	}

	try {
		if (order_info.value.lensQuantity == 1) {
			console.log("左眼单独配镜，右眼数量为0")
			// 左眼单独配镜，右眼数量为0
			formData.c_rnum = '0';
			formData.c_lnum = '1'; // 确保左眼数量为1
		} else if (order_info.value.lensQuantity == 2) {
			// 右眼单独配镜，左眼数量为0
			console.log("右眼单独配镜，左眼数量为0")
			formData.c_lnum = '0';
			formData.c_rnum = '1'; // 确保右眼数量为1
		} else if (order_info.value.lensQuantity == 0) {
			// 双眼配镜，确保两边数量都为1
			console.log("双眼配镜")
			formData.c_lnum = '1';
			formData.c_rnum = '1';
		}
		console.log('checkForm', formData);
		const result = await service.order.merchant.checkTongkangName(formData);
		console.log('check', result);
		submitForm();
		// submitFake();
		// ElMessage.success('订单检查通过')
		checkOrder.value = true
	} catch (error) {
		ElMessage.error(error.message);
	}
}

// 模拟表单提交
async function submitFake() {
	isSubmit.value = true;
	await sleep(10000);
	ElMessage.success('模拟-提交成功');
	isSubmit.value = false;
	// 关闭弹窗
	closeDialog();
}

// 提交表单
async function submitForm() {
	// 禁用点击按钮
	isSubmit.value = true;
	//   if (!checkOrder.value) {
	//       ElMessage.error('请先检查订单')
	//       return
	//   }
	// if (!formRef.value) return;

	try {
		await formRef.value.validate();

		// 这里是提交表单的逻辑，调用API提交数据
		console.log(order_info.value.lensQuantity, "镜片数量")
		console.log('提交的表单数据:', formData);
		if (formData.c_goods_l == '' || formData.c_goods_r == '') {
			ElMessage.error('请选择镜片');
			return;
		}
		// 根据code找到镜片的desc
		let goods_l_desc = '';
		let goods_r_desc = '';
		goodsList.value.forEach(item => {
			if (item.lens_code == formData.c_goods_l) {
				goods_l_desc = item.lens_desc;
			}
			if (item.lens_code == formData.c_goods_r) {
				goods_r_desc = item.lens_desc;
			}
		});
		formData.c_goods_l_desc = goods_l_desc;
		formData.c_goods_r_desc = goods_r_desc;
		// 查找加工的加工方式名称
		if (formData.c_process_type) {
			formData.c_process_type_name =
				processList.value.processType.find(item => item.value === formData.c_process_type)
					?.label || '';
		}
		// 查找加工的镀膜类型名称
		if (formData.c_coating_type) {
			formData.c_coating_type_name =
				processList.value.coatingType.find(item => item.value === formData.c_coating_type)
					?.label || '';
		}

		formData.order_id = props.orderId;
		formData.eyeglassImg = order_info.value.eyeglassImg;
		// 拼上收货数据
		// formData.contactName = shop_info.value.contactName
		// formData.contactPhone = shop_info.value.contactPhone
		// formData.receiveAddress = shop_info.value.receiveAddress

		// 模拟API调用
		// 实际项目中应替换为真实的API调用
		const res = await service.order.merchant.submitTongkangOrder(formData);
		console.log(res);
		// 模拟提交成功
		ElMessage.success('订单添加成功');
		isSubmit.value = false;
		// 关闭弹窗
		closeDialog();
	} catch (error) {
		console.error('表单验证失败:', error);
		isSubmit.value = false;
		ElMessage.error(error.message);
	}
}

const goodsList = ref([]);
// 添加一个响应式变量来跟踪当前选中的镜片是否需要显示下加光字段
const showAddFields = ref(false);

// 监听镜片选择的变化
watch(
	() => formData.c_goods_l,
	newValue => {
		if (newValue) {
			// 如果镜片改动则需要重置下加光数据
			// 如果是编辑则不重置
			if (!isEdit.value) {
				formData.c_ladd = '';
				formData.c_radd = '';
			}
			const selectedGoods = goodsList.value.find(item => item.lens_code === newValue);
			// 检查是否有 show_add 属性并设置 showAddFields
			showAddFields.value = selectedGoods && selectedGoods.show_add === true;
		} else {
			showAddFields.value = false;
		}
	}
);

// 当改变加工的时候重置加工里面的内容
watch(
	() => formData.c_is_process,
	newValue => {
		if (newValue === '0') {
			// 重置加工相关字段
			formData.c_process_type = '';
			// formData.c_coating_type = ''
			remarkObj.value.brand = '';
			remarkObj.value.model = '';
			remarkObj.value.frameColor = '';
			remarkObj.value.logisticsNo = '';
		}
	}
);

async function getTongkangGoods() {
	goodsList.value = await service.order.merchant.getTongkangGoodsListV2({
		orderId: props.orderId
	});
}

// 重置表单
function resetForm() {
	if (formRef.value) {
		formRef.value.resetFields();
		// 重置普通字段
		formData.c_lball = '';
		formData.c_rball = '';
		formData.c_lpole = '';
		formData.c_rpole = '';
		formData.c_goods_l = '';
		formData.c_goods_r = '';
		formData.c_goods_left_list = [];
		formData.c_goods_right_list = [];
		formData.c_lnum = '';
		formData.c_rnum = '';
		formData.c_ladd = '';
		formData.c_radd = '';
		formData.c_lline = '';
		formData.c_rline = '';
		formData.c_goods_l_desc = '';
		formData.c_goods_r_desc = '';
		formData.order_id = props.orderId;
		formData.c_is_process = '0';
		formData.pd_r = 0;
		formData.pd_l = 0;
		formData.ph_r = 0;
		formData.ph_l = 0;
		formData.c_process_type = '';
		formData.c_coating_type = '';
		checkOrder.value = false;
		formData.lensQuantity = -1; // 镜片数量
	}
	remarkObj.value = {
		brand: '',
		model: '',
		frameColor: '',
		logisticsNo: '',
		userName: '',
		remark: ''
	};
}

// 获取加工参数
async function getProcessParams() {
	const res = await service.order.merchant.getProcessParamsV2({
		orderId: props.orderId
	});
	console.log(res);
	processList.value.processType = res.c_process_type;
	processList.value.coatingType = res.c_coating_type;
}

// 关闭弹窗
function closeDialog() {
	console.log('props.currentOrderId', props.orderId, visible.value);
	emit('closeDialog');
}

async function syncGoods() {
	const res = await service.order.merchant.getGoodsType();
	console.log(res);
}

// 获取订单信息
async function getOrderDetail() {
	if (props.orderId) {
		try {
			// 调用API获取订单详情
			const res = await service.order.order.page({
				id: props.orderId
			});
			// console.log('getOrderDetail', res, res.data)
			if (res.list[0]) {
				// 标记为修改订单和查看
				isEdit.value = true;
				remarkObj.value.userName = '' + res.list[0].userNickName;
				order_info.value = res.list[0];
				formData.lensQuantity = res.list[0].lensQuantity; // 镜片类型
				// 如果已经填写过内容，则读取内容并赋值
				if (res.list[0].optometricsData) {
					// 将optometricsData字符串转为对象
					const optometricsData = JSON.parse(res.list[0].optometricsData);
					Object.assign(formData, optometricsData);
					// 查看是否已经有店铺信息，有则不用更新店铺地址信息
					if (formData.contactName != '' || formData.contactPhone != '' || formData.receiveAddress != '') {
						updateShopInfo.value = false;
					}
					console.log('formData', formData, res.list[0].optometricsData);
					// 根据remark拆分赋值给remarkObj
					if (optometricsData.remark) {
						const remarkParts = optometricsData.remark.split(',');
						remarkObj.value.userName = remarkParts[0];
						remarkObj.value.brand = remarkParts[1];
						remarkObj.value.model = remarkParts[2];
						remarkObj.value.frameColor = remarkParts[3];
						remarkObj.value.logisticsNo = remarkParts[4];
						remarkObj.value.remark = remarkParts[5];
					}
				}
			} else {
				ElMessage.error('获取订单详情失败');
			}
		} catch (error) {
			console.error('获取订单详情失败:', error);
			ElMessage.error('获取订单详情失败');
		}
	}
	getShopInfoByOrderId(props.orderId);
}

// 监听 modelValue 变化
watch(
	() => props.modelValue,
	val => {
		console.log('弹窗', val, props.orderId);
		if (val) {
			isEdit.value = false;
			getTongkangGoods();
			getOrderDetail();
			getProcessParams();
			// getShopInfoByOrderId(props.orderId)
		}
		visible.value = val;
	}
);

// 监听 visible 变化
watch(
	() => visible.value,
	val => {
		emit('update:modelValue', val);
		if (!val) {
			resetForm();
		}
	}
);

// 监听 formData 的变化，当任何字段改变时重置 checkOrder
watch(
	() => formData,
	() => {
		checkOrder.value = false;
	},
	{ deep: true }
);
</script>

<style scoped>
.zhongtian-add-order {
	padding: 20px;
}

.card-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.detail-item,
.payment-item {
	margin-bottom: 20px;
}

.detail-header,
.payment-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.border-top-blue {
	border-top: 3px solid #409eff;
}

.form-actions {
	margin-top: 30px;
	text-align: center;
}

.form-actions .el-button {
	margin: 0 10px;
}

/* 添加新的样式类 */
.inline-flex-container {
	display: flex;
	align-items: center;
	flex-wrap: wrap;
}
</style>
